/*
 * @Author: 吴世扬 18368095041@163.com
 * @Date: 2024-10-16 09:42:34
 * @LastEditors: 吴世扬 18368095041@163.com
 * @LastEditTime: 2024-10-16 11:09:57
 * @FilePath: /react18-vite-admin/src/views/system/RolesManage/components/useForm.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { useEffect, useState } from 'react';
import type { FormInstance } from 'antd';
import { immerable } from 'immer';
import { useImmer } from 'use-immer';

import { useRoleDetail, RoleParam } from '@/service/biz/role/useRoleDetail';
import { useEnumStore } from '@/store';

class FormModel extends RoleParam {
    [immerable] = true;
}

export const useForm = (
    formRef: FormInstance,
    id: number | undefined,
    open: boolean,
    afterSubmit: () => void
) => {
    const [title, setTitle] = useState('新增');

    const { saveRole, getDetail, loading, saveLoading } = useRoleDetail();

    const [formModel, setFormModel] = useImmer(new FormModel());
    
    const { menuTreeItems, handleUpdate } = useEnumStore();

    useEffect(() => {
        if (open) {
            formRef.resetFields();
            handleUpdate(['menuTreeItems']);
            console.log(222222, id)
            handleEdit(id);
        }
    }, [open]);

    const handleEdit = async (id?: number) => {
        const model = new FormModel();
        if (id) {
            setTitle('编辑');
            const res = await getDetail(id);
            model.id = res?.data.id;
            model.description = res?.data.description ?? '';
            model.menuIdList = res?.data.menuTree?.map((item) => item.id) || [];
            model.name = res?.data.name ?? '';
        } else {
            setTitle('新增');
        }
        setFormModel(model);
        formRef.setFieldsValue(model);
    };

    const handleSubmit = async () => {
        await saveRole(JSON.parse(JSON.stringify(formModel)));
        afterSubmit();
    };

    return {
        title,
        handleSubmit,
        handleEdit,
        formModel,
        setFormModel,
        menuTreeItems,
        loading,
        saveLoading
    };
};
